package com.bosssoft.boss_exam_core.common.Timer;

import com.bosssoft.boss_exam_core.util.common.DateUtil;
import com.bosssoft.boss_exam_db.entity.Exam;
import com.bosssoft.boss_exam_db.service.busines.ExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/***
 * @Author lys(cherish)
 * @Description 定时操作工具
 * @Date  2019/2/26
 **/
@Component
@Slf4j
public class CloseExamScheduler {

    public CloseExamScheduler(){
    }
    //线程任务执行的”结果“
    private ScheduledFuture<?> future;

    //线程池任务定时器注入
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    @Autowired
    private ExamService examService;

    /***
     * @Author lys(cherish)
     * @Description 启动定时，定时为单次具体时间日期执行
     * @Date  2019/2/26
     * @Param [task, sendTime] 任务、任务执行时间
     * @return void
     **/
    public void startCron(Date time,Exam exam) {
        System.out.println("开始定时了");
//        Cron expression must consist of 6 fields (found 7 in "00 03 21 23 03 ? 2019")
        String cron = DateUtil.getCron(time).split("[?]")[0] + "?";
        future = threadPoolTaskScheduler.schedule(new CloseExamRunnable(exam,examService), new CronTrigger(cron));
    }

    /***
     * @Author lys(cherish)
     * @Description 停止定时，暂未使用
     * @Date  2019/2/26
     * @Param []
     * @return void
     **/
    public void stopCron() {
        if (future != null) {
            future.cancel(true);
        }
        log.info("停止定时任务");
    }

    /***
     * @Author lys(cherish)
     * @Description 修改定时，暂未使用
     **/
//    public void startCron10() {
//        // 先停止，在开启.
//        stopCron();
//        future = threadPoolTaskScheduler.schedule(new CloseExamRunnable(), new CronTrigger("*/10 * * * * *"));
//        logger.info("修改定时");
//    }

}
